#!/usr/bin/env python
# encoding: utf-8

"""
@author: Cao
@contact: caoqiang0012@163.com
@file: PicCompare.py
@time: 10/7/2017 1:50 PM
"""
from PIL import Image, ImageChops
import os

class PicCompare():
    def __init__(self, sourcePic_path, targetPic_Path, Result_Pic):
        self.sourcePic_path = sourcePic_path
        self.targetPic_Path = targetPic_Path
        self.Result_Pic = Result_Pic

    def Comp(self):
        im1 = Image.open(self.sourcePic_path)
        im2 = Image.open(self.targetPic_Path)
        im3 = ImageChops.invert(im2)
        resultPic = Image.blend(im1, im3, 0.5).save(self.Result_Pic, "PNG")
        return resultPic

def Count(path):
    ls = os.listdir(path)
    count = 0
    for i in ls:
        if os.path.isfile(os.path.join(path, i)):
            count += 1
    return count

if __name__ == '__main__':
    s_path = "D:/test/s/"
    t_path = "D:/test/t/"
    result_path = "D:/test/r3/"

    if Count(s_path) != Count(t_path):
        print ('The Count of files are not equal, please check it!')
    else:
        if os.path.exists(result_path):
            count = Count(t_path)
            for i in range(1, count + 1):
                s_file = s_path + "s" + str(i) + ".png"
                t_file = t_path + "t" + str(i) + ".png"
                r_file = result_path + "r" + str(i) + ".png"
                PicCompare(s_file, t_file, r_file).Comp()
        else:
            print "Derectory is not Existing, will create it now, please wait......."
            os.mkdir(result_path)
            count = Count(t_path)
            for i in range(1, count + 1):
                s_file = s_path + "s" + str(i) + ".png"
                t_file = t_path + "t" + str(i) + ".png"
                r_file = result_path + "r" + str(i) + ".png"
                PicCompare(s_file, t_file, r_file).Comp()

    print "Job Complete!"
    print "Please see the result in Directory " +"*** " + result_path + " ***"